package com.xinyue.common.core.page;

import com.alibaba.fastjson2.JSONObject;
import com.xinyue.common.core.text.Convert;
import com.xinyue.common.utils.ServletUtils;

/**
 * 表格数据处理
 *
 * @author ruoyi
 */
public class TableSupport {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        boolean isGetMethod = ServletUtils.getRequest().getMethod().equalsIgnoreCase("get");


        if (isGetMethod) {
            return getFromGetMethod();
        } else {
            return getFromPostMethod();
        }

    }

    private static PageDomain getFromPostMethod() {
        PageDomain pageDomain = new PageDomain();
        String body = ServletUtils.getBodyString(ServletUtils.getRequest());
        JSONObject json = JSONObject.parseObject(body);
        pageDomain.setOrderByColumn(json.getString(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(json.getString(IS_ASC));
        pageDomain.setReasonable(json.getBoolean(REASONABLE));
        pageDomain.setPageNum(Convert.toInt(json.getObject(PAGE_NUM, Object.class)));
        pageDomain.setPageSize(Convert.toInt(json.getObject(PAGE_SIZE, Object.class)));
        return pageDomain;

    }

    private static PageDomain getFromGetMethod() {
        PageDomain pageDomain = new PageDomain();
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
        pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
        return pageDomain;
    }

    public static PageDomain buildPageRequest() {
        return getPageDomain();
    }
}
